import glob
import pandas as pd
from ModuleMaker import ModuleMaker
from OraWorker import OraWorker



def converter(row:pd.Series)->pd.Series:
    # row["Доп параметр2"]=float(str(row["Доп параметр2"]).replace(",","."))
    row["Код"] = row["Вид материала в SAP ERP"][:4]
    return row

def ntd_convert(row:pd.Series,ntd_cols:list,ora:OraWorker)->pd.Series:
    ntd = "".join([str(row[key]) for key in ntd_cols])
    # product_up = ora.product_check("*",row["ID в SAP ERP VMZ"])
    row["НТД качества"]=ntd.replace("nan","")
    # row["Продукт УП"] = product_up[0]
    return row

def get_nearest(guidName:str,query:str,nearestColumn:str,nearestValue:float,valueColumn:str):
    df = pd.read_csv(guidName,encoding="windows-1251",delimiter=";")
    df=df.apply(converter,axis=1)
    df = df.query(query)
    df_res = df.iloc[(df[nearestColumn]-nearestValue).abs().argsort()[:1]]
    return df_res[valueColumn].values[0]

if __name__=="__main__":
    
    r = ModuleMaker.make_from_file("handlers2\\module_pattern.py","key","ww_test_module")
    print(r)
    
    # "ID в SAP ERP VMZ","Полное наименование материала","Вид материала в SAP ERP","Производство"
    # cols1 = ["ID в SAP ERP VMZ","Полное наименование материала","Вид материала в SAP ERP","Производство"]
    # path_pattern="D:\\work\\Укрупнение\\current\\data\\2*\\*.xlsx"
    # exclude_pattern = "нение_"
    # files=[f for f in glob.glob(path_pattern) if exclude_pattern not in f] if exclude_pattern is not None else [f for f in glob.glob(path_pattern)]
    # frames = []
    # ora = OraWorker("sapnwc","sapnwc","172.17.80.116/scpora",".\\ora")
    # for f in files:
    #     try:
    #         xl  = pd.ExcelFile(f)
    #         for sheet in xl.sheet_names:
    #             df = pd.read_excel(f,sheet_name=sheet)
    #             df["file"]=f
    #             df["sheet"]=sheet
    #             ntd_cols_q = [col for col in df.columns if "НТД" in col and "ачества" in col and "*" not in col]
    #             ntd_cols_cover = [col for col in df.columns if "НТД" in col and "окрытия" in col and "3" not in col]
    #             steel_cols = [col for col in df.columns if "стал" in col or "проч" in col]
    #             if not df.empty: 
    #                 df = df.apply(lambda r: ntd_convert(r,ntd_cols_q,ora),axis=1)
    #                 frames.append(df[cols1+["НТД качества"]+steel_cols+ntd_cols_cover+["file","sheet"]])
    #                 print(f"{f}[{sheet}] added")
    #     except Exception as exp1:
    #         print(f"{f} failed: {exp1}")
    # result=pd.concat(frames)
    # result = result.drop_duplicates()
    # result = result.apply(converter,axis=1)
    # ntd_cols_cover = [col for col in result.columns if "НТД" in col and "покрытия" in col and "3" not in col]
    # steel_cols = [col for col in df.columns if "стал" in col or "проч" in col]
    # ora.close()
    # result[cols1+["Код","НТД качества"]+steel_cols+ntd_cols_cover+["file","sheet"]].to_excel("output\\VM_Productions3.xlsx",index=False)
            
    
    